﻿using System;
using System.Collections.Generic;
using System.Linq;
using CRM.Extensions;

namespace CRM
{
    public static class Helper
    {
        /// <summary>
        /// 创建固定hashcode
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static long GetDeterministicHashCode(string str) => str.GetFixedHashCode();


        /// <summary>
        /// 日期转换为时间戳Timestamp
        /// </summary>
        /// <param name="dateTime"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static long GetTimeStamp(DateTime dateTime,int type = 1)
        {
            DateTime _dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
            long timeStamp = 0;
            if (type == 1)
            {
                //10位的时间戳
                timeStamp = Convert.ToInt32(dateTime.Subtract(_dtStart).TotalSeconds);
            }
            else {
                //13位的时间戳
                timeStamp = Convert.ToInt64(dateTime.Subtract(_dtStart).TotalMilliseconds);
            }

            return timeStamp;
        }

        /// <summary>
        /// 获取当前时间戳 10位的时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetNowTimeStamp()
        {
            return GetTimeStamp(DateTime.Now);
        }

        /// <summary>
        /// UTC时间戳Timestamp转换为北京时间
        /// </summary>
        /// <param name="timestamp">要转换的时间戳</param>
        /// <returns></returns>
        public static DateTime GetDateTime(long timestamp)
        {
            //DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            //使用上面的方式会显示TimeZone已过时
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            long lTime = long.Parse(timestamp + "0000000");
            TimeSpan timeSpan = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(timeSpan).AddHours(8);
            return targetDt;
        }

        /// <summary>
        /// 时间戳转换日期
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static string TimeStampToDate(long timestamp) {
            return GetDateTime(timestamp).ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 时间戳转换日期时间  24小时制
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static string TimeStampToDateTime(long timestamp) {
            return GetDateTime(timestamp).ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 10进制转换成62进制
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string From10to62(long number)
        {
            char[] charSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
            var str = string.Empty;
            var num = number;
            while (num > 0)
            {
                long val = num % 62;
                str = charSet[val] + str;
                num = num / 62;
            }
            return str;
        }

        /// <summary>
        /// 62进制转换成10进制
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal From62to10(string value)//bUI6zOLZTrj
        {
            string keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//编码,可加一些字符也可以实现72,96等任意进制转换，但是有符号数据不直观，会影响阅读。
            decimal result = 0;
            for (int i = 0; i < value.Length; i++)
            {
                int x = value.Length - i - 1;
                result += keys.IndexOf(value[i]) * Pow(62, x);// Math.Pow(exponent, x);
            }
            return result;
        }

        /// <summary>
        /// 一个数据的N次方
        /// </summary>
        /// <param name="baseNo"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        private static decimal Pow(decimal baseNo, decimal x)
        {
            decimal value = 1;////1 will be the result for any number's power 0.任何数的0次方，结果都等于1
            while (x > 0)
            {
                value = value * baseNo;
                x--;
            }
            return value;
        }
        /// <summary>
        /// 检测输入的手机号strPhone是否合法，非法则返回true。
        /// </summary>
        public static bool CheckPhone(string strPhone)
        {
            if(strPhone.Length == 11)
            {
                return System.Text.RegularExpressions.Regex.IsMatch(strPhone, @"^[1]+[\d]+\d{9}");
            }
            return false;
        }
        /// <summary>
        /// 检测输入的邮件地址strEmail是否合法，非法则返回true。
        /// </summary>
        public static bool CheckEmail(string strEmail)
        {
            int i, j;
            string strTmp, strResult;
            string strWords = "abcdefghijklmnopqrstuvwxyz_-.0123456789"; //定义合法字符范围
            bool blResult = false;
            strTmp = strEmail.Trim();
            //检测输入字符串是否为空，不为空时才执行代码。
            if (!(strTmp == null || strTmp.Length == 0))
            {
                //判断邮件地址中是否存在“@”号
                if ((strTmp.IndexOf("@") < 0))
                {
                    blResult = true;
                    return blResult;
                }
                //以“@”号为分割符，把地址切分成两部分，分别进行验证。
                string[] strChars = strTmp.Split(new char[] { '@' });
                foreach (string strChar in strChars)
                {
                    i = strChar.Length;
                    //“@”号前部分或后部分为空时。
                    if (i == 0)
                    {
                        blResult = true;
                        return blResult;
                    }
                    //逐个字进行验证，如果超出所定义的字符范围strWords，则表示地址非法。
                    for (j = 0; j < i; j++)
                    {
                        strResult = strChar.Substring(j, 1).ToLower();
                        if (strWords.IndexOf(strResult) < 0)
                        {
                            blResult = true;
                            return blResult;
                        }
                    }
                }
            }
            return blResult;
        }
        
        /// <summary>
        /// 获取所有子类
        /// </summary>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        [Obsolete("不要频繁调用")]
        public static IEnumerable<Type> GetSubClasses(Type sourceType)
        {
            var subClasses = from type in sourceType.Assembly.GetTypes()
                where type.IsSubclassOf(sourceType)
                select type;
            return subClasses;
        }
        
        public static string FormatCsvField(string field)
        {
            if (field == null)
                return string.Empty;

            var result = field.Trim();
            result = result.Replace("\"", "\"\""); // 替换英文冒号 英文冒号需要换成两个冒号
            if (result.Contains(",") || result.Contains("\"") || result.Contains("\r") || result.Contains("\n")) // 含逗号 冒号 换行符的需要放到引号中
            {
                result = string.Format("\"{0}\"", result);
            }
            return result;
        }
    }
}